package com.ugoodtech.mdcc.web.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.StationLeanPaintSatisfactionReport.OperationalDataAnalysis;
import com.ugoodtech.mdcc.core.domain.StationLeanPaintSatisfactionReport.QOperationalDataAnalysis;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.utils.AnswerOtherUtil;
import com.ugoodtech.mdcc.core.utils.ArrayStringUtil;
import com.ugoodtech.mdcc.core.utils.DateUtil;
import com.ugoodtech.mdcc.core.utils.ValidateUtil;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.KpiDataRequest;
import com.ugoodtech.mdcc.web.dto.KpiDataResponse;
import com.ugoodtech.mdcc.web.service.UserLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api(description = "精益钣喷报告相关接口")
@RestController
@RequestMapping("/paintReport")
public class VstarPaintReportController extends BaseController{

    private static final Logger logger = LoggerFactory.getLogger(VstarPaintReportController.class);

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private StationPaintReportRepository stationPaintReportRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private OperationalDataAnalysisRepository operationalDataAnalysisRepository;

    @Autowired
    private com.ugoodtech.mdcc.web.service.StationPaintReport stationPaintReport;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private UserLogService userLogService;

    private static Integer[] index = new Integer[7];

    static {
        for (int i = 0; i < index.length; i++) {
            index[i] = i;
        }
    }

    @ApiOperation("修改精益钣喷报告")
    @RequestMapping(value = "editPaintReport", method = RequestMethod.POST)
    public JsonResponse editPaintReport(@ApiParam("登陆用户ID") @RequestParam(value = "loginUserId") Long loginUserId,
                                        @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId,
                                        @ApiParam("问题ID") @RequestParam(value = "questionId") Long questionId,
                                        @ApiParam("答案ID") @RequestParam(value = "answerId", required = false) String answerId,
                                        @ApiParam("填空") @RequestParam(value = "answerOther", required = false) String answerOther,
                                        @ApiParam("照片") @RequestParam(value = "answerPhoto", required = false) String answerPhoto) {
        isUserLogin();
        if (questionId == 172L) {
            return JsonResponse.errorResponseWithError("抱歉", "此题无法在此修改");
        }
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
        if (reportId == null || reportId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "报告ID数据异常");
        }
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null || !stationReport.getCategory().equals(Constants.PAINT_REPORT)) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该报告或此报告不是精益钣喷报告");
        }
        if (questionId == null || questionId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "问题ID数据异常");
        }
        StationPaintReport stationPaintReport = stationPaintReportRepository.selectAnswerByQuestion(reportId, questionId);
        if (stationPaintReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此题答案");
        }
        //修改
        String originAnswerId = stationPaintReport.getAnswerId();
        String originAnswerOther = stationPaintReport.getAnswerOther();


        stationPaintReport.setAnswerId(answerId);
        stationPaintReport.setAnswerOther(answerOther);
        stationPaintReport.setAnswerPhoto(answerPhoto);
        stationPaintReportRepository.save(stationPaintReport);
        try {

            if (!filterAnswerOther(originAnswerOther).equals(filterAnswerOther(answerOther)) ||
                    (null != answerId&&!filterAnswerId(originAnswerId).equals(answerId))) {
                    Map<String, Object> data = new HashMap<>();
                    String desc = "";
                    Question question = questionRepository.findOne(questionId);
                    desc += question.getSubject() + ":";
                    desc += getAnswerString(originAnswerId) + filterAnswerOther(originAnswerOther) + "-->>" + getAnswerString(answerId) + filterAnswerOther(answerOther)+",";
                    data.put("str", desc);
                    String stationNum = "";
                    if (null != stationReport.getStation()) {
                        stationNum = stationReport.getStation().getStationNum();
                    }
                    if (!StringUtils.isEmpty(desc)) {
                        userLogService.addUserLog(user, stationNum, reportId, Constants.PAINT_REPORT, LogConstants.operate_type_edit, LogConstants.business_type_lean_paint_report, null, data);
                    }
                }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResponse.successResponse();
    }


    @ApiOperation("获取提交的精益板喷KPI数据")
    @RequestMapping(value = "getData", method = RequestMethod.GET)
    public JsonResponse getKpiData(@ApiParam("报告ID") @RequestParam(value = "reportId", required = false) Long reportId,
                                   @ApiParam("维修站ID") @RequestParam(value = "stationId") Long stationId) {
        isUserLogin();
        if (reportId == null || reportId == 0) {
            List<KpiDataResponse> kpiDataResponseList = new ArrayList<>();
            for (int i = 0; i < 7; i++) {
                KpiDataResponse kpiDataResponse = new KpiDataResponse();
                kpiDataResponse.setIndexId(i);
                kpiDataResponseList.add(kpiDataResponse);
            }
            return JsonResponse.successResponseWithData(kpiDataResponseList);
        }
        QOperationalDataAnalysis qOperationalDataAnalysis = QOperationalDataAnalysis.operationalDataAnalysis;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qOperationalDataAnalysis.deleted.eq(false));
        builder.and(qOperationalDataAnalysis.enabled.eq(true));
        builder.and(qOperationalDataAnalysis.reportId.eq(reportId));
        builder.and(qOperationalDataAnalysis.stationId.eq(stationId));
        builder.and(qOperationalDataAnalysis.indexId.in(index));
        List<OperationalDataAnalysis> operationalDataAnalysisList = (List<OperationalDataAnalysis>) operationalDataAnalysisRepository.findAll(builder, new Sort(Sort.Direction.ASC, "indexId"));
        if (operationalDataAnalysisList == null || operationalDataAnalysisList.size() <= 0) {
            List<KpiDataResponse> kpiDataResponseList = new ArrayList<>();
            for (int i = 0; i < 7; i++) {
                KpiDataResponse kpiDataResponse = new KpiDataResponse();
                kpiDataResponse.setIndexId(i);
                kpiDataResponseList.add(kpiDataResponse);
            }
            return JsonResponse.successResponseWithData(kpiDataResponseList);
        }
        List<KpiDataResponse> kpiDataResponseList = new ArrayList<>();
        for (OperationalDataAnalysis data : operationalDataAnalysisList) {
            KpiDataResponse kpiDataResponse = new KpiDataResponse(data);
            kpiDataResponseList.add(kpiDataResponse);
        }
        return JsonResponse.successResponseWithData(kpiDataResponseList);
    }


    @ApiOperation("移动")
    @RequestMapping(value = "changeKpiData", method = RequestMethod.GET)
    public JsonResponse changeKpiData(Long loginUserId,
                                      @ApiParam("报告ID") @RequestParam(value = "reportId", required = false) Long reportId,
                                      @ApiParam("维修站ID") @RequestParam(value = "stationId") Long stationId,
                                      @ApiParam("前移或者后移") @RequestParam(value = "upDown") boolean upDown,
                                      @ApiParam("移动位数") @RequestParam(value = "moveIndex") Integer moveIndex) {
        isUserLogin();
        User clientUser = userRepository.findOne(loginUserId);
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        if (reportId == null || reportId == 0 || moveIndex >= 7) {
            List<KpiDataResponse> kpiDataResponseList = new ArrayList<>();
            for (int i = 0; i < 7; i++) {
                KpiDataResponse kpiDataResponse = new KpiDataResponse();
                kpiDataResponse.setIndexId(i);
                kpiDataResponseList.add(kpiDataResponse);
            }
            return JsonResponse.successResponseWithData(kpiDataResponseList);
        }

        QOperationalDataAnalysis qOperationalDataAnalysis = QOperationalDataAnalysis.operationalDataAnalysis;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qOperationalDataAnalysis.deleted.eq(false));
        builder.and(qOperationalDataAnalysis.enabled.eq(true));
        builder.and(qOperationalDataAnalysis.reportId.eq(reportId));
        builder.and(qOperationalDataAnalysis.stationId.eq(stationId));
        builder.and(qOperationalDataAnalysis.indexId.in(index));
        List<OperationalDataAnalysis> operationalDataAnalysisList = (List<OperationalDataAnalysis>) operationalDataAnalysisRepository.findAll(builder);
        List<KpiDataResponse> kpiDataResponseList = new ArrayList<>();
        for (OperationalDataAnalysis data : operationalDataAnalysisList) {
            KpiDataResponse kpiDataResponse = new KpiDataResponse(data);
            kpiDataResponseList.add(kpiDataResponse);
        }

        for (int i = 0; i < moveIndex; i++) {
            KpiDataResponse k0 = kpiDataResponseList.get(0);
            k0.setIndexId(1);
            KpiDataResponse k1 = kpiDataResponseList.get(1);
            k1.setIndexId(2);
            KpiDataResponse k2 = kpiDataResponseList.get(2);
            k2.setIndexId(3);
            KpiDataResponse k3 = kpiDataResponseList.get(3);
            k3.setIndexId(4);
            KpiDataResponse k4 = kpiDataResponseList.get(4);
            k4.setIndexId(5);
            KpiDataResponse k5 = kpiDataResponseList.get(5);
            k5.setIndexId(6);
            KpiDataResponse k6 = kpiDataResponseList.get(6);
            if (upDown == true) {
                KpiDataResponse kpiDataResponse = new KpiDataResponse();
                kpiDataResponse.setReportId(k0.getReportId());
                kpiDataResponse.setStationId(k0.getStationId());
                kpiDataResponse.setId(k0.getId());
                k0.setId(k1.getId());
                k1.setId(k2.getId());
                k2.setId(k3.getId());
                k3.setId(k4.getId());
                k4.setId(k5.getId());
                k5.setId(k6.getId());
                kpiDataResponseList.set(0, kpiDataResponse);
                kpiDataResponseList.set(1, k0);
                kpiDataResponseList.set(2, k1);
                kpiDataResponseList.set(3, k2);
                kpiDataResponseList.set(4, k3);
                kpiDataResponseList.set(5, k4);
                kpiDataResponseList.set(6, k5);
            } else {
                KpiDataResponse kpiDataResponse = new KpiDataResponse();
                kpiDataResponse.setReportId(k6.getReportId());
                kpiDataResponse.setStationId(k6.getStationId());
                kpiDataResponse.setId(k6.getId());
                kpiDataResponse.setIndexId(6);

                k6.setId(k5.getId());
                k6.setIndexId(5);
                k5.setId(k4.getId());
                k5.setIndexId(4);
                k4.setId(k3.getId());
                k4.setIndexId(3);
                k3.setId(k2.getId());
                k3.setIndexId(2);
                k2.setId(k1.getId());
                k2.setIndexId(1);
                k1.setId(k0.getId());
                k1.setIndexId(0);

                kpiDataResponseList.set(6, kpiDataResponse);
                kpiDataResponseList.set(5, k6);
                kpiDataResponseList.set(4, k5);
                kpiDataResponseList.set(3, k4);
                kpiDataResponseList.set(2, k3);
                kpiDataResponseList.set(1, k2);
                kpiDataResponseList.set(0, k1);
            }
        }
        return JsonResponse.successResponseWithData(kpiDataResponseList);
    }

    @ApiOperation("创建精益钣喷KPI数据")
    @RequestMapping(value = "createKpiData", method = RequestMethod.POST)
    public JsonResponse createKpiData(Long loginUserId,
                                      @RequestBody KpiDataRequest kpiDataRequest,
                                      @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId,
                                      @ApiParam("维修站ID") @RequestParam(value = "stationId") Long stationId,
                                      @ApiParam("问题ID") @RequestParam(value = "questionId") Long questionId,
                                      @ApiParam("填空") @RequestParam(value = "answerOther") String answerOther) {
        isUserLogin();
        if (questionId != 172L) {
            return JsonResponse.errorResponseWithError("抱歉", "题目ID错误，请传入改善月题目ID");
        }
        User clientUser = userRepository.findOne(loginUserId);
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        if (reportId == null || reportId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "报告ID数据异常");
        }
        if (stationId == null || stationId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "维修站ID数据异常");
        }
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null || !stationReport.getCategory().equals(Constants.PAINT_REPORT)) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该报告或此报告不是精益钣喷报告");
        }
        Station station = stationRepository.findOne(stationId);
        if (station == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此维修站");
        }
        List<OperationalDataAnalysis> operationalDataObjects = kpiDataRequest.getOperationalDataAnalysisList();
        if (operationalDataObjects.size() != 7) {
            return JsonResponse.errorResponseWithError("抱歉", "改善月数据有异常，请检查");
        }
        logger.info("<<<<<<<<<<<<<<<<<<重新设置改善月>>>>>>>>>>>>>>>>>");
        StationPaintReport stationPaintReport_answer = stationPaintReportRepository.selectAnswerByQuestion(reportId, questionId);
        stationPaintReport_answer.setAnswerOther(answerOther);

        logger.info("<<<<<<<<<<<<<<<<<<提交的表格数量为：" + operationalDataObjects.size() + ">>>>>>>>>>>>>>>>>");
        QOperationalDataAnalysis operationalDataAnalysis = QOperationalDataAnalysis.operationalDataAnalysis;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(operationalDataAnalysis.deleted.eq(false));
        builder.and(operationalDataAnalysis.enabled.eq(true));
        builder.and(operationalDataAnalysis.reportId.eq(reportId));
        builder.and(operationalDataAnalysis.stationId.eq(stationId));
        List<OperationalDataAnalysis> operationalDataAnalysisList = (List<OperationalDataAnalysis>) operationalDataAnalysisRepository.findAll(builder);
        logger.info("<<<<<<<<<<<<<<<<<<将原来的表格数据逻辑删除>>>>>>>>>>>>>>>>>");
        for (OperationalDataAnalysis unFinished : operationalDataAnalysisList) {
            unFinished.setDeleted(true);
            unFinished.setEnabled(false);
            operationalDataAnalysisRepository.save(unFinished);
        }
        logger.info("<<<<<<<<<<<<<<<<<<新增新的表格数据>>>>>>>>>>>>>>>>>");
        for (OperationalDataAnalysis operationalData : operationalDataObjects) {
            operationalData.setStationId(stationId);
            operationalData.setReportId(reportId);
            operationalDataAnalysisRepository.save(operationalData);
        }
        stationPaintReportRepository.save(stationPaintReport_answer);
        logger.info("<<<<<<<<<<<<<<<<<<改善月设置完毕>>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<开始计算表格中的数据>>>>>>>>>>>>>>>>>");
        return stationPaintReport.calculateKpiData(reportId, stationId);
    }

    String getAnswerString(String answerIds) {
        List<String> answers = new ArrayList<>();
        List<Long> answerIdArray = ArrayStringUtil.getStringIds(answerIds);
        for (Long answerId : answerIdArray) {
            QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(answerId);
            answers.add(questionAnswerOption.getName());
        }
        return StringUtils.join(answers, ",");
    }

    String filterAnswerOther(String answerOther) {
        try {
            Long currentMin = Long.parseLong(answerOther);
            if (currentMin > 1000000) {
                Date date = new Date(currentMin);
                if(!ValidateUtil.isValidMobileNo(answerOther)){
                    return DateUtil.formatDate(date, Constants.DATE_FORMAT);
                }else{
                    return AnswerOtherUtil.getOtherString(answerOther);
                }
            } else {
                return AnswerOtherUtil.getOtherString(answerOther);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AnswerOtherUtil.getOtherString(answerOther);
        }
    }

    String filterAnswerId(String answerIds) {
        if (null == answerIds) {
            return "";
        } else {
            return answerIds;
        }
    }


}
